/* eslint-disable import/no-dynamic-require */
/* eslint-disable global-require */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row,
  Col,
  Card,
  Badge,
  List,
  Typography,
  Avatar,
  Modal,
  Transfer,
  message,
  Spin,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Img from '@/assets/defaultImg.png';
import EditLink from './EditLink';
import styles from './style.less';

const { Paragraph } = Typography;

@connect(({ login, menu, workplace, loading }) => ({
  login,
  menu,
  workplace,
  chosenKeys: workplace.chosenKeys,
  loading: loading.models.workplace,
}))
@Form.create()
class WorkPlace extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      shortcutVisible: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'workplace/searchWaitTask',
    });
    dispatch({
      type: 'workplace/searchNotice',
    });
    dispatch({
      type: 'workplace/searchFunParams',
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'workplace/updateModalData',
      payload: {
        shortcutChosen: [],
        shortcutList: [],
        waitTaskData: [],
        shortcutData: [],
        noticeData: [],
        chosenKeys: [],
      },
    });
  }

  // 获取用户头像
  getAvatarURL() {
    const {
      login: { baseUser },
    } = this.props;
    if (baseUser.userPortrait) {
      const fileId = baseUser.userPortrait;
      return `/mgrApi/fileServer/showImage?fileId=${fileId}`; // 后台返回
    }
    const url = Img; // 默认的
    return url;
  }

  onExpand = item => {
    const tempItem = item;
    tempItem.retractFlag = true;
  };

  // 快速开始中添加新项
  handleAddLink = flag => {
    const { dispatch } = this.props;
    dispatch({
      type: 'workplace/searchShortcutList',
      payload: {},
    });
    this.setState({
      shortcutVisible: flag,
    });
  };

  // 点取消时弹框隐藏
  handleCancle = () => {
    this.setState({
      shortcutVisible: false,
    });
  };

  // 从工作台往具体也没跳转
  jumpRouting = targetRouter => {
    const routerParams = {
      pathname: `${targetRouter.url}/index`,
      query: {
        isMenuLink: false,
        activeKey:
          targetRouter.sysId === 'BS0000000001' &&
          targetRouter.url === '/customservicemanage/addemployee'
            ? '4'
            : targetRouter.activeKey,
      },
    };
    if (targetRouter.queryParam) {
      routerParams.queryParam = targetRouter.queryParam;
    }
    router.push(routerParams);
  };

  // 穿梭框中左右移动项目事件
  handleChange = (targetKeys, direction, moveKeys) => {
    const { chosenKeys, dispatch } = this.props;
    const tempKeys = JSON.parse(JSON.stringify(chosenKeys));
    if (direction === 'right') {
      moveKeys.forEach(item => {
        tempKeys.push(item);
      });
    } else {
      moveKeys.forEach(item => {
        tempKeys.splice(tempKeys.indexOf(item), 1);
      });
    }
    dispatch({
      type: 'workplace/updateModalData',
      payload: {
        chosenKeys: tempKeys,
      },
    });
  };

  // 新增快速开始事件
  addFunction = () => {
    // const { shortcutChosenKeys } = this.state;
    const { dispatch, chosenKeys } = this.props;
    this.setState({
      shortcutVisible: false,
    });
    dispatch({
      type: 'workplace/addFunction',
      payload: {
        funIds: chosenKeys,
      },
    }).then(res => {
      if (res.success) {
        dispatch({
          type: 'workplace/searchFunParams',
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    });
  };

  // 点击更多
  more = () => {
    router.push({
      pathname: `/more/message/index`,
      query: {
        activeKey: '3',
      },
    });
  };

  filterOption = (inputValue, option) => option.functionName.indexOf(inputValue) > -1;

  // 显示当前时间状态
  getTimeState = () => {
    // 获取当前时间
    const timeNow = new Date(); // 获取当前小时
    const hours = timeNow.getHours(); // 设置默认文字
    let text = ``; // 判断当前时间段
    if (hours >= 0 && hours <= 10) {
      text = `早上`;
    } else if (hours > 10 && hours <= 14) {
      text = `中午`;
    } else if (hours > 14 && hours <= 18) {
      text = `下午`;
    } else if (hours > 18 && hours <= 24) {
      text = `晚上`;
    }
    return text;
  };

  render() {
    const {
      login: { baseUser },
      workplace: { waitTaskData, shortcutData, noticeData, shortcutList },
      chosenKeys,
      loading,
    } = this.props;
    const { shortcutVisible } = this.state;

    const pageHeaderContent = (
      <div className={styles.pageHeaderContent}>
        <div className={styles.avatar}>
          <Avatar size="large" src={this.getAvatarURL()} />
        </div>
        <div className={styles.content}>
          <div className={styles.contentTitle}>
            {this.getTimeState()}好，{baseUser.userName}
            ，祝你开心每一天！
          </div>
          <div>
            {baseUser.corpName} | {baseUser.orgName}
          </div>
        </div>
      </div>
    );
    return (
      <PageHeaderWrapper content={pageHeaderContent}>
        <Spin spinning={loading}>
          <Row gutter={24} className={styles.workPlace}>
            <Col xl={16} lg={24} md={24} sm={24} xs={24}>
              <Card
                className={styles.projectList}
                style={{ marginBottom: 16 }}
                title="待处理任务"
                bordered={false}
                bodyStyle={{ padding: '24px 0 4px' }}
              >
                <Row gutter={24}>
                  {waitTaskData && waitTaskData.length ? (
                    waitTaskData.map(item => (
                      <Col md={8} sm={24} key={item.tskId}>
                        <Card
                          bordered
                          bodyStyle={{ padding: 0 }}
                          style={{ height: 106, marginBottom: 16 }}
                        >
                          <h3>{item.tskName}</h3>
                          <div className={styles.media}>
                            <img src={require(`../../../assets/${item.imgCode}.png`)} alt="" />
                            <span
                              style={{
                                display: 'inline-block',
                                marginLeft: 16,
                                verticalAlign: -17,
                                maxWidth: '93px',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap',
                              }}
                              title={item.taskCount}
                              className={
                                Number(item.taskCount) === 0 || !item.taskCount ? styles.gray : ''
                              }
                            >
                              {item.taskCount || '0'}
                            </span>
                            {item.taskCount && Number(item.taskCount) !== 0 ? (
                              <a
                                style={{ float: 'right', marginTop: 19 }}
                                onClick={() => {
                                  this.jumpRouting(item);
                                }}
                              >
                                立即办理
                              </a>
                            ) : null}
                          </div>
                        </Card>
                      </Col>
                    ))
                  ) : (
                    <span style={{ display: 'block', margin: '0 0 24px 24px', fontSize: 14 }}>
                      暂无数据
                    </span>
                  )}
                </Row>
              </Card>
            </Col>
            <Col xl={8} lg={24} md={24} sm={24} xs={24}>
              <Card
                extra={
                  <a style={{ cursor: 'pointer' }} onClick={() => this.more()}>
                    更多
                  </a>
                }
                style={{ marginBottom: 16 }}
                title="公告"
                bordered={false}
                bodyStyle={{ padding: '4px 24px' }}
              >
                <List
                  className={styles.tipList}
                  bordered={false}
                  dataSource={noticeData}
                  locale={{ emptyText: '无公告内容' }}
                  renderItem={item => (
                    <List.Item>
                      <List.Item.Meta
                        title={
                          <div>
                            <Paragraph ellipsis={{ rows: 2 }}>
                              <Badge
                                status="default"
                                text={<span style={{ color: '#eb822c' }}>[{item.title}]</span>}
                              />
                              {item.content}
                            </Paragraph>
                          </div>
                        }
                        description={
                          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                            <span>{item.userTypeName}</span>
                            <span>{moment(item.creTime).format('YYYY-MM-DD HH:mm:ss')}</span>
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              </Card>
              <Card
                style={{ marginBottom: 16 }}
                title="快捷方式"
                bordered={false}
                bodyStyle={{ paddingTop: 8 }}
              >
                <EditLink data={shortcutData} handleAddLink={this.handleAddLink} />
              </Card>
            </Col>
          </Row>
        </Spin>
        <Modal
          title="请选择菜单"
          visible={shortcutVisible}
          destroyOnClose
          onCancel={this.handleCancle}
          width={600}
          onOk={this.addFunction}
          style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
        >
          <Transfer
            rowKey={record => record.funId}
            listStyle={{
              width: 240,
              height: 400,
            }}
            dataSource={shortcutList}
            showSearch
            filterOption={this.filterOption}
            targetKeys={chosenKeys}
            onChange={this.handleChange}
            render={item => item.functionName}
          />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default WorkPlace;
